package com.qms.tubu.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.qms.tubu.R;

/**
 * Created by Mad on 2015/7/2.
 */
public class CycleRadioGroup extends RadioGroup{
    private Paint circlePaint;
    public CycleRadioGroup(Context context) {
        super(context);
        initPaint();
    }

    public CycleRadioGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        initPaint();
    }
    private void initPaint()
    {
        circlePaint=new Paint(Paint.ANTI_ALIAS_FLAG);
        circlePaint.setColor(getResources().getColor(R.color.cycle_radio_btn_color));
        circlePaint.setStrokeWidth(getResources().getDimension(R.dimen.cycle_radio_stroke_width));
    }
    public void updateChild(int num)
    {
        int childNum=getChildCount();
        if(childNum<num)
        {
            for(int i=childNum;i<num;i++)
            {
                this.addView(generateButton(i));
            }
        }
        else if(childNum>num)
        {
            for(int i=childNum-1;i>=num;i--)
                this.removeView(getChildAt(i));
        }
    }
    private CycleRadioButton generateButton(int id)
    {
        CycleRadioButton button=new CycleRadioButton(this.getContext());
        int width=getResources().getDimensionPixelOffset(R.dimen.cycle_radio_button_size);
        RadioGroup.LayoutParams params=new RadioGroup.LayoutParams(width,width);
        int margin=getResources().getDimensionPixelOffset(R.dimen.cycle_radio_margin_size);
        params.setMargins(margin,0,margin,0);
        button.setLayoutParams(params);
        button.setId(id);
        return button;
    }
    private class CycleRadioButton extends RadioButton{

        public CycleRadioButton(Context context) {
            super(context);
            this.setEnabled(false);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            int width=getMeasuredWidth()/2;
            int radius= (int) (width-circlePaint.getStrokeWidth());
            if(isChecked())
            {
                circlePaint.setStyle(Paint.Style.FILL_AND_STROKE);
                canvas.drawCircle(width,width,radius,circlePaint);
            }
            else
            {
                circlePaint.setStyle(Paint.Style.STROKE);
                canvas.drawCircle(width,width,radius,circlePaint);
            }
        }
    }
}
